package zzu.mxd.answer.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import zzu.mxd.answer.vo.AnswerResult;
import zzu.mxd.answer.entity.Exercises;
import zzu.mxd.answer.service.IExercisesService;
import zzu.mxd.answer.vo.ExercisesVO;
import zzu.mxd.common.PageRequest;
import zzu.mxd.common.R;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 题目表 前端控制器
 * </p>
 *
 * @author mxd
 * @since 2018-11-08
 */
@Api(tags = "习题管理")
@RestController
@RequestMapping("/answer/exercises")
@Slf4j
public class ExercisesController {

    @Autowired
    private IExercisesService exercisesService;


    @ApiOperation("增加题目")
    @PostMapping()
    public R<String> add(@RequestBody Exercises exercises) {
        exercisesService.save(exercises);
        return R.succ();
    }



    /**
     * 测试通过
     *
     * @param exercises
     * @param request
     * @return
     */
    @ApiOperation("分页条件查询题目")
    @PostMapping("/selectPage")
    public R<IPage<Exercises>> selectPage(@RequestBody Exercises exercises, PageRequest request) {
        IPage<Exercises> page = new Page<>(request.getCurrent(), request.getSize());
        page = exercisesService.page(page, new QueryWrapper<>(exercises));
        return R.succC(page);
    }

    /**
     * 从redis中获取习题：指定科目ID、题数
     *
     * @param count     题数
     * @param subjectId 科目ID
     * @return
     */
    @ApiOperation("从redis中获取题目")
    @PostMapping("/selectFromRedis")
    public R<List<Exercises>> selectFromRedis(Integer count, int subjectId) {


        try {
            return R.succC(exercisesService.getRandomExercises(count, subjectId));
        } catch (Exception e) {
            e.printStackTrace();
            return R.errM("获取题库错误");
        }
    }

    /**
     * @param exercisesVOList
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation("学生答题")
    @PutMapping("/{id}")
    public R<AnswerResult> answer(@RequestParam("exercisesVOList") String exercisesVOList, @PathVariable String id) throws Exception {
        List<ExercisesVO> vos = JSON.parseArray(exercisesVOList, ExercisesVO.class);
        AnswerResult answerResult = exercisesService.answerQuestion(vos,id);
        return R.succC(answerResult);

    }




}
